/*
 * CCSQLPaginaDAO.java
 *
 * Created on 8 de noviembre de 2007, 15:59
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package webportlet.model.pagina.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import webportlet.model.pagina.dto.PaginaDTO;
import webportlet.model.util.DuplicateInstanceException;
import webportlet.model.util.EntityIdentifierRetriever;
import webportlet.model.util.EntityIdentifierRetrieverFactory;
import webportlet.model.util.GeneralOperations;
import webportlet.model.util.InternalErrorException;

/**
 *
 * @author Administrador
 */
public class CCSQLPaginaDAO extends AbstractSQLPaginaDAO {
    
   public PaginaDTO create(Connection connection, PaginaDTO paginaDTO) 
        throws DuplicateInstanceException, InternalErrorException{
        
        if (exists(connection, paginaDTO.getNickName())) {
            throw new DuplicateInstanceException(paginaDTO.getNickName(),
                PaginaDTO.class.getName());
        }

        PreparedStatement preparedStatement = null;
    
        try {

            /* Create "preparedStatement". */
            String queryString = "INSERT INTO Pagina" +
                " (nickName, numNoticias)" +
                " VALUES (?, ?)";
            preparedStatement = connection.prepareStatement(queryString);    
            
            /* Fill "preparedStatement". */
            int i = 1;
            preparedStatement.setString(i++, paginaDTO.getNickName());
            preparedStatement.setInt(i++, paginaDTO.getNumNoticias());
                        
            /* Execute query. */
            int insertedRows = preparedStatement.executeUpdate();
        
            if (insertedRows == 0) {
                throw new SQLException("Can not add row to table" +
                    " 'Pagina'");
            }

            if (insertedRows > 1) {
                throw new SQLException("Duplicate row for nickName = '" + 
                    paginaDTO.getNickName() + "' in table 'Pagina'");
            }
            EntityIdentifierRetriever entityIdentifierRetriever = 
                    EntityIdentifierRetrieverFactory.getRetriever();
            Long id=entityIdentifierRetriever.getGeneratedIdentifier(connection);
            return new PaginaDTO(new Long(id), paginaDTO.getNickName(),
                    paginaDTO.getNumNoticias());
        
        } catch (SQLException e) {
            throw new InternalErrorException(e);
        } finally {
            GeneralOperations.closeStatement(preparedStatement);
        }  
    }
    
}
